<?php

/**
 * photo actions.
 *
 * @package    sfwixet
 * @subpackage photo
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class photoActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('photo', 'get');
  }
  
  public function executeMoveTo(sfWebRequest $request)
  {
  	if(strlen($request->getParameter("photo")) == 32 && is_numeric($request->getParameter("album")))
  	{
  		try{
  		$album = Doctrine::getTable("album")->find($request->getParameter("album"));
  		$photo = Doctrine::getTable("photo")->find($request->getParameter("photo"));

  			if($album->getOwnerId() == $this->getUser()->getId() && $photo->getOwnerId() == $this->getUser()->getId())
  			{
  				$old = $photo->getAlbumId();
  				$photo->setAlbumId($album->getAlbumId());
  				$photo->save();
  				echo json_encode(array("error"=>false, "oldAlbum"=>$old, "newAlbum"=>$photo->getAlbumId()));
  			} else throw new AclException(_("Permission denied"));
  		}catch(Exception $e){
  			echo json_encode(array("error"=>true,"message"=>_("Permission denied")));
  		}
  	}else echo json_encode(array("error"=>true,"message"=>_("Please specify an album id and photo id")));
  	
  	return sfView::NONE;
  }
  
  public function setTitle(sfWebRequest $request)
  {
  	
  }
  
  public function executeGetTags(sfWebRequest $request){
  	try{
  		$photo = Doctrine::getTable("photo")->find($request->getParameter("id"));
  		$tags = array();
  		foreach($photo->getTags() as $tag)
  		{
  			$tagArr=$tag->toArray();
  			$tagArr['user']=array("name"=>$tag->getUserTagged()->getFirstName()." ".$tag->getUserTagged()->getLastName(),"id"=>$tag->getUserId());
  			$tags[] = $tagArr;
  		}
  		echo json_encode($tags);
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>_("Permission denied")));
  	}
  	return sfView::NONE;
  }
  
  public function executeNewTag(sfWebRequest $request){
  	try{
  		$photo = Doctrine::getTable("photo")->find($request->getParameter("id"));
  		$friend = Doctrine::getTable("sfGuardUser")->find($request->getParameter("user_id"));
  		if($friend->isFriend($this->getUser()) || $friend->getId() == $this->getUser()->getId())
  		{
	  		$tag = new PhotoTag();
	  		$tag->setPhotoId($request->getParameter("id"));
	  		$tag->setUserId($friend->getId());
	  		$tag->setTaggerId($this->getUser()->getId());
	  		
	  		$tag->setXPosition($request->getParameter("x"));
	  		$tag->setYPosition($request->getParameter("y"));
	  		
	  		$tag->setWidth($request->getParameter("width"));
	  		$tag->setHeight($request->getParameter("height"));
	  		$tag->setNote($request->getParameter("note"));
	  		
	  		$tag->save();
	  		
	  		$notification = new PhotoTagNotification();
			$notification->setPhoto($photo);
			$notification->setUser($friend);
			$notification->save();
			$photo->touch();
  		}else throw new AclException("You only can tag friends");
				
  		echo json_encode(array("error"=>false));
  		//$this->forward('photo', 'getTags');
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
  	return sfView::NONE;
  }
  
  
  public function executeUpdateTag(sfWebRequest $request){
  	try{
  		$photo = Doctrine::getTable("photo")->find($request->getParameter("id"));
  		$tag = Doctrine::getTable("photoTag")->find(array($request->getParameter("id"),$request->getParameter("user_id")));
  		//Owner or tagged can edit the tag
  		if($photo->getOwnerId() == $this->getUser()->getId() || $tag->getUserId() == $this->getUser()->getId())
  		{
				$tag->setXPosition($request->getParameter("x"));
		  		$tag->setYPosition($request->getParameter("y"));
		  		
		  		$tag->setWidth($request->getParameter("width"));
		  		$tag->setHeight($request->getParameter("height"));
	  		
		  		$tag->setNote($request->getParameter("note"));
	 
	  		$tag->save();
	  		$this->forward('photo', 'getTags');
  		} else throw new AclException(_("Permission denied"));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>_("Permission denied")));
  	}
  	return sfView::NONE;
  }
  
  public function executeRemoveTag(sfWebRequest $request){
  	try{
  		$photo = Doctrine::getTable("photo")->find($request->getParameter("id"));
  		$tag = Doctrine::getTable("photoTag")->find(array($request->getParameter("id"),$request->getParameter("user_id")));
  		//Owner or tagged can edit the tag
  		if($photo->getOwnerId() == $this->getUser()->getId() || $tag->getUserId() == $this->getUser()->getId())
  		{
				$tag->delete();
	  		$this->forward('photo', 'getTags');
  		} else throw new AclException(_("Permission denied"));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>_("Permission denied")));
  	}
  	return sfView::NONE;
  }
  
  public function executeGet(sfWebRequest $request)
  {  	
  	try{
  		
  		$photo = Doctrine::getTable("photo")->find($request->getParameter("id"));
  		$owner = $photo->getOwner();
  		try{
  			$album = $photo->getAlbum();
  			$albumData = array("id"=>$album->getAlbumId(),"name"=>$album->getName());
  		}catch(AclException $e){
			$albumData = null;
  		}
  		
		$ownerData = array("id"=>$owner->getId(),"name"=>$owner->getUsername());
		
		
		$data = array("owner"=>$ownerData,"album"=>$albumData,"title"=>$photo->getTitle(),"visits"=>$photo->getVisits(),"date"=>$photo->getCreatedAt());
		echo json_encode($data);
  	}catch(AclException $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
	
	return sfView::NONE;
  }
  
  public function executeComments(sfWebRequest $request)
  {
  	
  	//$photo = Photo::secureLoad($request->getParameter("id"),$this->getUser()->getId());
  	try
  	{
  		//$this->pager = new sfDoctrinePager($photo->getComments(1,10),5);
		$photo = Doctrine::getTable("photo")->find($request->getParameter("id"));
  		$pager = $photo->getComments($request->getParameter("page",1),$request->getParameter("size",10));
  		//$results = $pager->getResults();

  			$textComments = array();
			foreach ($pager->getResults() as $comment)
			{
				$textComment = array();
				$author = $comment->getAuthor();
				$authorData = array();
				
				$authorData['name']=$author->getFistname()." ".$author->getLastname();
				$authorData['id']=$author->getId();
				$authorData['face']=$author->getFace()->getPhotoId();
				
				$textComment['comment'] = $comment->getComment();
				$textComment['author'] = $authorData;
				$textComment['date'] = $comment->getCreatedAt();
				
				$textComment['sound'] = $comment->getSound()->toArray();
				unset($textComment['sound']['uploader_id']);
				
				$textComments[] = $textComment;
			}
			
  		echo json_encode(array("comments"=>$textComments,"pagecount"=>$pager->getLastPage()));


  	}catch(AclException $e){
  		echo json_encode(array("error"=>true,"message"=>_("Permission denied")));
  	}
  	return sfView::NONE;
  }
  
  public function executeComment(sfWebRequest $request)
  {
  	try{
  		$result = array();
  		$photo = Doctrine::getTable("photo")->find($request->getParameter("id"));
  				
  		if($photo->comment($this->getUser(),$request->getParameter("content"),$request->getParameter("sound",null)))
  		{
  			$result['error'] = false;
  		}else{
  			$result['error'] = true;
  			$result['message'] = "Not comment";
  		}
  		echo json_encode($result);
  	}catch(AclException $e){
  		echo json_encode(array("error"=>true,"message"=>_("Permission denied")));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}	
  	return sfView::NONE;
  }
  
  public function executeImage(sfWebRequest $request){
  	try{
  		$photo = Doctrine::getTable("photo")->find($request->getParameter("id"));
   		$file = "../photos/".$photo->getId();
   		$filename = $photo->getTitle();
   		if(strlen($filename) == 0)
   			$filename = $photo->getId();
   			
   		$photo->setViews($photo->getViews()+1);
   		$photo->save();
   		    header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename="'.$filename.'.png"');
		    header('Content-Transfer-Encoding: binary');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($file));
		    
		    readfile($file);
  	}catch(AclException $e){
  		echo json_encode(array("error"=>true,"message"=>_("Permission denied")));
  	}	
  	return sfView::NONE;
  }
  
  public function executeThumbnail(sfWebRequest $request){
  	
  	try{
	  	$photo = Doctrine::getTable("Photo")->find($request->getParameter("id"));
		if($photo instanceof Photo){
		  	$response = $this->getResponse();
	
			$response->setContentType('image/jpeg');
			readfile("../photos/thumbnails/".$request->getParameter("type","mini")."/".$photo->getId());
		}else throw new Exception(_("This photo does not exists"));
		
  	}catch(Exception $e){
  		$response = $this->getResponse();
  		$response->setContentType('image/png');
		readfile("../photos/thumbnails/".$request->getParameter("type","mini")."/".sfConfig::get('sf_default_photo'));
  	}	

   	return sfView::NONE;
  }
  
  public function executeUpload(sfWebRequest $request){
  	
  if($request->getMethod() == sfRequest::POST) {
	if(function_exists("apc_fetch"))
  		$json = apc_fetch('upload_'.$request->getParameter("APC_UPLOAD_PROGRESS"));
  	else
  		$json = array();
  $json['error']=false;
  $json['done']=true;
  $json['uploadId']=$request->getParameter("APC_UPLOAD_PROGRESS");      
        //Guardamos las fotos
        foreach($_FILES as $file)
        {
                $error=false;
                //$formato = split("\.",$imagen['name']);
                //$formato = strtolower($formato[1]);
                $format = image_type_to_mime_type(exif_imagetype($file['tmp_name']));
                if($format=='image/jpeg' or $format == 'image/png')
                {

                        $json["error"] = false;
                        $photo = new Photo();
                        
                        $photo->setOwner($this->getUser());
                        try {
	                        $photo->setAlbum($this->getUser()->getGuardUser()->getMainAlbum());
						    //Guardamos siempre en png
	                        $img = null;
	                        if($format=='image/jpeg')
	                        	$img = imagecreatefromjpeg ($file['tmp_name']);
	                        else
	                        	$img = imagecreatefrompng ($file['tmp_name']);
	                        
	                        //check for file permissions
	                        if(is_writable(sfConfig::get('sf_root_dir')."/photos")
	                        	&& is_writable(sfConfig::get('sf_root_dir')."/photos/thumbnails/normal")
	                        	&& is_writable(sfConfig::get('sf_root_dir')."/photos/thumbnails/list")
	                        	&& is_writable(sfConfig::get('sf_root_dir')."/photos/thumbnails/mini"))
	                        {
	                        	$name = md5_file($file['tmp_name']);//Old m5
								$imagePath = sfConfig::get('sf_root_dir')."/photos/tmp_".$name;
		                        //ImagePng($img,$imagePath);
		                        imagejpeg($img,$imagePath);
		                        $name = md5_file($imagePath);
		                        rename($imagePath,sfConfig::get('sf_root_dir')."/photos/".$name);
		                        $imagePath = sfConfig::get('sf_root_dir')."/photos/".$name;
		                        $photo->setPhotoId($name);
		                        $photo->save();
		                        
		                        $json["id"] = $name;
		                        
		                        $normalThumbnail = new sfThumbnail(500, 500);
		                        $listThumbnail = new sfThumbnail(150, 150);
		                        $miniThumbnail = new sfThumbnail(50, 50);
		                        
		  						$normalThumbnail->loadFile($imagePath);
		  						$normalThumbnail->save(sfConfig::get('sf_root_dir')."/photos/thumbnails/normal/".$name, 'image/jpeg');
		                        
		  						$listThumbnail->loadFile($imagePath);
		  						$listThumbnail->save(sfConfig::get('sf_root_dir')."/photos/thumbnails/list/".$name, 'image/jpeg');
		  						
		  						$miniThumbnail->loadFile($imagePath);
		  						$miniThumbnail->save(sfConfig::get('sf_root_dir')."/photos/thumbnails/mini/".$name, 'image/jpeg');
		  						
		  						//Really not necessary
		  						//$photo->grantAllToGroup($this->getUser()->getGuardUser()->getMainGroup());
		  						$photo->touch();
	                        }else throw new Exception("Thumbnails or photos directories are not writable");
						} catch (Doctrine_Connection_Mysql_Exception $e) {
						    //Photo already exists
						     $json["error"] = true;
                			$json["message"] = _('This photo already exists');
						} catch (Exception $e){
							 $json["error"] = true;
                				$json["message"] = ($e->getMessage().' Please contact with the administrator');
							 $photo->delete();
						}

                }
                else
                {
                	$json["error"] = true;
                	$json["message"] =_("Only PNG and JPG format are allowed");
                }


        }
        
        ///////////////////
		 $this->result = $json;
		} else if($request->getParameter("progress_key") != null) {
			if(function_exists("apc_fetch"))
		 	 	$this->result = apc_fetch('upload_'.$request->getParameter("progress_key"));
		 	else
		 		$this->result = array("current"=>25,"total"=>100);
		 		
		} else if($request->getParameter("get_key") != null) {
		        $this->result = array("uuid"=>uniqid());

		}
  	
  }
  
  public function executePermissionsDetails(sfWebRequest $request)
  {
	try
  	{
  		$photo = Doctrine::getTable("Photo")->find($request->getParameter("id"));
  		if($photo->getOwnerId()==$this->getUser()->getId())
  		{
  			$allowedGroups = array();
  			$deniedGroups = array();
  			$groups = $this->getUser()->getGuardUser()->getMyAclGroups();
  			foreach($groups as $group){
  				$permissions = $photo->getPhotoPermissionsForGroup($group);
  				if($permissions['read_granted'])
  					$allowedGroups[] = $group->toArray();
  					
  				if($permissions['read_denied'])
  					$deniedGroups[] = $group->toArray();	
  			}
			
  			//This function is used to allow array_udiff to compare groups
  			/*function groupsCompare($group1,$group2)
  			{
  				//if($group1['group_id'] == $group2['group_id'] ? 0:1)
  					echo $group1['group_name']."(".$group1['group_id'].") ==".$group2['group_name']."(".$group2['group_id'].") ".($group1['group_id'] == $group2['group_id'] ? 0:1)."<br>";
  					
  					//echo $group1['group_id'] == $group2['group_id'] ? 0:1;
  				return $group1['group_id'] === $group2['group_id'] ? 0:1;
  			}
			$undefinedAllowedGroups = array_udiff($groups->toArray(),$allowedGroups,"groupsCompare");
			*/
  			
			$undefinedAllowedGroups = $groups->toArray();
			$tam = $groups->count();
			foreach($allowedGroups as $allowedGroup){
				$continue = true;
				 $index = 0;
				while($continue && $index<$tam){
					$continue = $allowedGroup['group_id'] != $undefinedAllowedGroups[$index]['group_id'];
					$index++;
				}
				if(!$continue) unset($undefinedAllowedGroups[$index-1]);
			}

			
			//$undefinedDeniedGroups = array_udiff($groups->toArray(),$deniedGroups,"groupsCompare");
			
  			$undefinedDeniedGroups = $groups->toArray();
			$tam = $groups->count();
			foreach($deniedGroups as $deniedGroup){
				$continue = true;
				 $index = 0;
				while($continue && $index<$tam){
					$continue = $deniedGroup['group_id'] != $undefinedDeniedGroups[$index]['group_id'];
					$index++;
				}
				if(!$continue) unset($undefinedDeniedGroups[$index-1]);
			}
			
  			echo json_encode(array("allowedGroups"=>$allowedGroups,"deniedGroups"=>$deniedGroups,"undefinedAllowedGroups"=>$undefinedAllowedGroups,"undefinedDeniedGroups"=>$undefinedDeniedGroups));
  		}else{
  			throw new AclException(_("Permission denied"));
  		}
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>_("Permission denied")));
  	}	
    return sfView::NONE;
  }
  
  public function executeNewPermissions(sfWebRequest $request){
  	try
  	{
  		$photo = Doctrine::getTable("Photo")->find($request->getParameter("id"));
  		if($photo->getOwnerId()==$this->getUser()->getId())
  		{
  			$permissions = json_decode($request->getParameter("permissions"));
  			if($request->isMethod(sfRequest::POST))
  			{
  				//Reset permissions
  				Doctrine::getTable("aclPhotoGroup")->findByPhotoId($photo->getId())->delete();
	  			foreach($permissions->allowed as $groupId){
	  				
					$group = Doctrine::getTable("aclGroup")->find($groupId->id);
					if($group->getOwnerId() == $this->getUser()->getId())
					{
						$photo->grantReadToGroup($group);
						$photo->grantWriteToGroup($group);
					}
  				}
  			
				foreach($permissions->denied as $groupId){
	  				
					$group = Doctrine::getTable("aclGroup")->find($groupId->id);
					if($group->getOwnerId() == $this->getUser()->getId())
					{
						$photo->denyReadToGroup($group);
						$photo->denyWriteToGroup($group);
					}
  				}

  				echo json_encode(array("error"=>false));
  			}else echo json_encode(array("error"=>true,"message"=>_("You should post the allowed and denied groups")));
  		}else{
  			throw new AclException(_("Permission denied"));
  		}
  	}catch(Doctrine_Table_Exception $e){
  		echo json_encode(array("error"=>true,"message"=>_("Internal error:").$e->getMessage()));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>_("Permission denied")));
  	}
  	

    return sfView::NONE;
  }
  
  public function executeRemove(sfWebRequest $request){
  	try{
  		$photo = Doctrine::getTable("Photo")->find($request->getParameter("id"));
  		$photoName = $photo->getPhotoId();
  		$user = $photo->delete();
  		unlink(sfConfig::get('sf_root_dir')."/photos/".$photoName);
  		unlink(sfConfig::get('sf_root_dir')."/photos/thumbnails/normal/".$photoName);
  		unlink(sfConfig::get('sf_root_dir')."/photos/thumbnails/list/".$photoName);
  		unlink(sfConfig::get('sf_root_dir')."/photos/thumbnails/mini/".$photoName);  

                          		
  		echo json_encode(array("error"=>false));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
  	return sfView::NONE; 
  }
  
}
